<template>
  <div class="work-reports-layout">
    <!-- 顶部导航 -->
    <div class="work-reports-header">
      <div class="header-left">
        <h2 class="page-title">
          <el-icon><Document /></el-icon>
          {{ $t('workReports.title') }}
        </h2>
        <p class="page-description">{{ $t('workReports.subtitle') }}</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="quickGenerateReport">
          <el-icon><Star /></el-icon>
          {{ $t('workReports.layout.quickGenerate') }}
        </el-button>
      </div>
    </div>

    <!-- 导航标签页 -->
    <div class="work-reports-tabs">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane :label="$t('workReports.layout.tabs.records')" name="records">
          <template #label>
            <span class="tab-label">
              <el-icon><Edit /></el-icon>
              {{ $t('workReports.layout.tabs.records') }}
            </span>
          </template>
        </el-tab-pane>
        <el-tab-pane :label="$t('workReports.layout.tabs.generate')" name="generate">
          <template #label>
            <span class="tab-label">
              <el-icon><Star /></el-icon>
              {{ $t('workReports.layout.tabs.generate') }}
            </span>
          </template>
        </el-tab-pane>
        <el-tab-pane :label="$t('workReports.layout.tabs.manage')" name="manage">
          <template #label>
            <span class="tab-label">
              <el-icon><Folder /></el-icon>
              {{ $t('workReports.layout.tabs.manage') }}
            </span>
          </template>
        </el-tab-pane>
        <el-tab-pane :label="$t('workReports.layout.tabs.statistics')" name="statistics">
          <template #label>
            <span class="tab-label">
              <el-icon><DataAnalysis /></el-icon>
              {{ $t('workReports.layout.tabs.statistics') }}
            </span>
          </template>
        </el-tab-pane>
        <el-tab-pane :label="$t('workReports.layout.tabs.settings')" name="settings">
          <template #label>
            <span class="tab-label">
              <el-icon><Setting /></el-icon>
              {{ $t('workReports.layout.tabs.settings') }}
            </span>
          </template>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 内容区域 -->
    <div class="work-reports-content">
      <router-view />
    </div>

    <!-- 快速生成报告对话框 -->
    <el-dialog
      v-model="quickGenerateVisible"
      :title="$t('workReports.layout.quickDialog.title')"
      width="500px"
      :before-close="handleQuickGenerateClose"
    >
      <div class="quick-generate-content">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card
              class="quick-option"
              :class="{ disabled: quickGenerating }"
              @click="generateTodayReport"
            >
              <div class="option-icon">
                <el-icon size="32" v-if="!quickGenerating"><Calendar /></el-icon>
                <el-icon size="32" v-else class="rotating"><Loading /></el-icon>
              </div>
              <div class="option-title">{{ $t('workReports.layout.quickDialog.dailyReport') }}</div>
              <div class="option-desc">
                {{ quickGenerating ? $t('workReports.layout.quickDialog.generating') : $t('workReports.layout.quickDialog.dailyDesc') }}
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card
              class="quick-option"
              :class="{ disabled: quickGenerating }"
              @click="generateWeekReport"
            >
              <div class="option-icon">
                <el-icon size="32" v-if="!quickGenerating"><Timer /></el-icon>
                <el-icon size="32" v-else class="rotating"><Loading /></el-icon>
              </div>
              <div class="option-title">{{ $t('workReports.layout.quickDialog.weeklyReport') }}</div>
              <div class="option-desc">
                {{ quickGenerating ? $t('workReports.layout.quickDialog.generating') : $t('workReports.layout.quickDialog.weeklyDesc') }}
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card
              class="quick-option"
              :class="{ disabled: quickGenerating }"
              @click="generateMonthReport"
            >
              <div class="option-icon">
                <el-icon size="32" v-if="!quickGenerating"><Calendar /></el-icon>
                <el-icon size="32" v-else class="rotating"><Loading /></el-icon>
              </div>
              <div class="option-title">{{ $t('workReports.layout.quickDialog.monthlyReport') }}</div>
              <div class="option-desc">
                {{ quickGenerating ? $t('workReports.layout.quickDialog.generating') : $t('workReports.layout.quickDialog.monthlyDesc') }}
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useWorkReportStore } from '@/stores/workReportStore'
import { ElMessage } from 'element-plus'
import {
  Document,
  Edit,
  Star,
  Folder,
  DataAnalysis,
  Setting,
  Calendar,
  Timer,
  Loading
} from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const workReportStore = useWorkReportStore()

// 响应式数据
const activeTab = ref('records')
const quickGenerateVisible = ref(false)
const quickGenerating = ref(false)

// 监听路由变化，同步标签页状态
watch(
  () => route.name,
  (newName) => {
    if (newName === 'WorkRecords') {
      activeTab.value = 'records'
    } else if (newName === 'ReportGenerate') {
      activeTab.value = 'generate'
    } else if (newName === 'ReportManage') {
      activeTab.value = 'manage'
    } else if (newName === 'WorkStatistics') {
      activeTab.value = 'statistics'
    } else if (newName === 'WorkReportSettings') {
      activeTab.value = 'settings'
    }
  },
  { immediate: true }
)

// 标签页切换
const handleTabChange = (tabName: string) => {
  const routeMap: Record<string, string> = {
    records: 'WorkRecords',
    generate: 'ReportGenerate',
    manage: 'ReportManage',
    statistics: 'WorkStatistics',
    settings: 'WorkReportSettings'
  }
  
  const routeName = routeMap[tabName]
  if (routeName && route.name !== routeName) {
    router.push({ name: routeName })
  }
}

// 快速生成报告
const quickGenerateReport = () => {
  quickGenerateVisible.value = true
}

// 关闭快速生成对话框
const handleQuickGenerateClose = () => {
  quickGenerateVisible.value = false
}

// 生成今日日报
const generateTodayReport = async () => {
  if (quickGenerating.value) return // 防止重复点击

  try {
    quickGenerating.value = true
    ElMessage.info('开始生成今日日报，请稍候...')
    await workReportStore.generateTodayReport()
    quickGenerateVisible.value = false
    // 跳转到报告生成页面查看结果
    router.push({ name: 'ReportGenerate' })
  } catch (error) {
    console.error('生成今日日报失败:', error)
  } finally {
    quickGenerating.value = false
  }
}

// 生成本周周报
const generateWeekReport = async () => {
  if (quickGenerating.value) return // 防止重复点击

  try {
    quickGenerating.value = true
    ElMessage.info('开始生成本周周报，请稍候...')
    const report = await workReportStore.generateReport({
      type: 'WEEKLY',
      startDate: getWeekStart(),
      endDate: getWeekEnd()
    })
    quickGenerateVisible.value = false
    router.push({ name: 'ReportGenerate' })
  } catch (error) {
    console.error('生成本周周报失败:', error)
  } finally {
    quickGenerating.value = false
  }
}

// 生成本月月报
const generateMonthReport = async () => {
  if (quickGenerating.value) return // 防止重复点击

  try {
    quickGenerating.value = true
    ElMessage.info('开始生成本月月报，请稍候...')
    const report = await workReportStore.generateReport({
      type: 'MONTHLY',
      startDate: getMonthStart(),
      endDate: getMonthEnd()
    })
    quickGenerateVisible.value = false
    router.push({ name: 'ReportGenerate' })
  } catch (error) {
    console.error('生成本月月报失败:', error)
  } finally {
    quickGenerating.value = false
  }
}

// 获取本周开始日期
const getWeekStart = (): string => {
  const today = new Date()
  const dayOfWeek = today.getDay()
  const diff = today.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1) // 周一为一周开始
  const monday = new Date(today.setDate(diff))
  return monday.toISOString().split('T')[0]
}

// 获取本周结束日期
const getWeekEnd = (): string => {
  const today = new Date()
  const dayOfWeek = today.getDay()
  const diff = today.getDate() - dayOfWeek + (dayOfWeek === 0 ? 0 : 7) // 周日为一周结束
  const sunday = new Date(today.setDate(diff))
  return sunday.toISOString().split('T')[0]
}

// 获取本月开始日期
const getMonthStart = (): string => {
  const today = new Date()
  return new Date(today.getFullYear(), today.getMonth(), 1).toISOString().split('T')[0]
}

// 获取本月结束日期
const getMonthEnd = (): string => {
  const today = new Date()
  return new Date(today.getFullYear(), today.getMonth() + 1, 0).toISOString().split('T')[0]
}

// 组件挂载时初始化数据
onMounted(() => {
  // 获取分类数据
  workReportStore.fetchCategories()
})
</script>

<style scoped lang="scss">
.work-reports-layout {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--el-bg-color-page);
}

.work-reports-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 24px;
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-light);

  .header-left {
    .page-title {
      margin: 0 0 4px 0;
      font-size: 20px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      display: flex;
      align-items: center;
      gap: 6px;
    }

    .page-description {
      margin: 0;
      color: var(--el-text-color-regular);
      font-size: 13px;
    }
  }

  .header-right {
    .el-button {
      height: 32px;
      padding: 0 16px;
      font-size: 14px;
    }
  }
}

.work-reports-tabs {
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-light);
  padding: 0 24px;

  :deep(.el-tabs__header) {
    margin: 0;
  }

  :deep(.el-tabs__nav-wrap::after) {
    display: none;
  }

  :deep(.el-tabs__item) {
    height: 40px;
    line-height: 40px;
    font-size: 14px;
  }

  :deep(.el-tabs__nav) {
    border: none;
  }

  .tab-label {
    display: flex;
    align-items: center;
    gap: 6px;
  }
}

.work-reports-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px 20px;
}

.quick-generate-content {
  .quick-option {
    cursor: pointer;
    text-align: center;
    transition: all 0.3s ease;
    border: 2px solid transparent;

    &:hover:not(.disabled) {
      border-color: var(--el-color-primary);
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    &.disabled {
      cursor: not-allowed;
      opacity: 0.6;

      &:hover {
        transform: none;
        box-shadow: none;
        border-color: transparent;
      }
    }

    .option-icon {
      margin-bottom: 12px;
      color: var(--el-color-primary);
    }

    .option-title {
      font-size: 16px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      margin-bottom: 8px;
    }

    .option-desc {
      font-size: 12px;
      color: var(--el-text-color-regular);
    }
  }
}

// 旋转动画
.rotating {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
